package xintegral

import (
	"time"

	"gitee.com/xiaoyutab/xgotool/optional/xnsq"
	"gitee.com/xiaoyutab/xgotool/xerror"
)

// 创建/修改积分信息
//
//	c	积分主表存储的信息
func CreateIntegral(c *Integral) error {
	if c.UserId <= 0 {
		return xerror.New("积分所属人不能为空")
	}
	if _default.DB == nil {
		return xerror.New("数据库未连接")
	}
	create := false
	if c.Id <= 0 {
		create = true
	}
	if c.CreatedAt == "" {
		c.CreatedAt = time.Now().Format(time.DateTime)
	}
	c.UpdatedAt = time.Now().Format(time.DateTime)
	if c.Type == 0 {
		c.Type = 3 // 默认无限期积分
	} else if c.Type > 4 {
		return xerror.New("积分分类错误")
	}
	if c.EndDate == "" {
		c.EndDate = time.Now().Format(time.DateOnly)
	}
	err := _default.DB.Save(c).Error
	if err != nil {
		return err
	}
	xnsq.Set(_default.HookIntegralEdit, c)
	if create && c.Balance > 0 {
		CreateHistory(c.Id, int(c.Balance), "账户初始化", false)
	}
	return nil
}
